package com.zyx.camunda.common.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.extra.spring.SpringUtil;
import org.camunda.bpm.engine.IdentityService;
import org.camunda.bpm.engine.delegate.Expression;
import org.camunda.bpm.engine.impl.pvm.delegate.ActivityExecution;

import java.util.*;

/**
 * @author zyx
 * @since 2023/9/21 09:23
 */
public class CamundaUtils {

    private static final IdentityService identityService = SpringUtil.getBean(IdentityService.class);

    public static void setAuth(String userId) {
        identityService.setAuthentication(userId, ListUtil.empty(), Collections.singletonList("zyx"));
    }

    public static void clearAuth() {
        identityService.clearAuthentication();
    }

    public static Object getElementObject(ActivityExecution execution, int loopCounter, Expression collectionExpression, String collectionVariable) {
        Collection<?> collection = null;
        if (collectionExpression != null) {
            collection = (Collection<?>) collectionExpression.getValue(execution);
        } else if (collectionVariable != null) {
            collection = (Collection<?>) execution.getVariable(collectionVariable);
        }
        return getElementAtIndex(loopCounter, Objects.requireNonNull(collection));
    }

    private static Object getElementAtIndex(int i, Collection<?> collection) {
        Object value = null;
        int index = 0;
        Iterator<?> it = collection.iterator();
        while (index <= i) {
            value = it.next();
            index++;
        }
        return value;
    }

}
